import Dep from "./dep";

export default class Observer {
  constructor(data) {
    this.traverse(data);
  }
  /**
   * 递归遍历data里的所有属性
   */
  traverse(data) {
    if (!data || typeof data !== "object") return;
    Object.keys(data).forEach((key) => {
      this.defineReactive(data, key, data[key]);
    });
  }

  /** `每个属性`都创建并拥有一个Dep */
  defineReactive(obj, key, val) {
    this.traverse(val);
    const dep = new Dep();
    const that = this;
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get: function reactiveGetter() {
        if (Dep.target) {
          // dep.depend(); // 有target(watcher)的收集到数组里
          dep.addSub(Dep.target);
        }
        return val;
      },
      set: function reactiveSetter(newVal) {
        if (newVal === val || (newVal !== newVal && val !== val)) {
          return;
        }
        val = newVal;
        that.traverse(newVal); // 设置的可能是对象
        dep.notify();
      },
    });
  }
}
